<template>
	<view class="padding bg-white ">
		<view class="bg-container">
			<view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage" :data-url="imgList[index]">
				<image :src="imgList[index]" mode="aspectFill"></image>
				<view style="position: absolute; bottom: 0px; right: 0px;" class="text-xl" @tap.stop="DelImg" :data-index="index">
					<text class='cuIcon-deletefill text-red'></text>
				</view>
			</view>
			<view class="option" @tap="ChooseImage">
				<view class="text-lg"  v-if="imgList.length==0">
					<text class='cuIcon-cameraadd'></text>
					<text class="padding-left">点击此处上传图片</text>
				</view>
			</view>
		</view>
		
	</view>
</template>


<script>
	import upload from "@/wx-cos/upload.js";
	export default {
		props: {
			value: [String],
			idKey: {
				type: String,
				default: ''
			},
			img: {
				type: String,
				default: ''
			},
		},
		data: function() {
			return {
				imgList: []
			};
		},
		mounted: function() {
			if (this.value) {
				this.imgList.push(this.value);
			}
		},
		methods: {
			ChooseImage() {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						this.imgList = res.tempFilePaths
						
						let filepath = this.imgList[0];
						
						upload.checkUploadFile(filepath, this.idKey, "cover", 
						pro => {
							console.log(pro)
						}).then(data => {
							this.imgList[0] = data.url;
							this.$emit("input", data.url);
							this.$forceUpdate();
						});

					}
				});
			},
			ViewImage(e) {
				uni.previewImage({
					urls: this.imgList,
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(e) {
				uni.showModal({
					title: '删除确认',
					content: '确定要删除这个图片吗？',
					cancelText: '取消',
					confirmText: '确认',
					success: res => {
						if (res.confirm) {
							this.imgList.splice(e.currentTarget.dataset.index, 1);
							this.$emit("change", "");
						}
					}
				})
			},
		}
	}
</script>

<style scoped>
	.bg-container {
		height: 5rem;
		display: flex;
		justify-content: start;
		position: relative;
	}
	.option {
		position: absolute;
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100%;
		width: 100%;
		top:0;
	}
	.bg-img {
		position: relative;
		display: flex;
		justify-content: start;
		align-items: center;
		height: 5rem;
		width: 5rem;
	}
	
	.bg-img image {
		width: 5rem;
		height: 5rem;
	}
</style>